<?php 
namespace XFCore\traits\user;

trait QrlistTrait {
    
    // 支付宝配置
    protected $alipayConfigs = [
        4 => [
            'fields' => [
                'alipaymck_uid' => '支付宝UID',
                'alipaymck_appid' => '支付宝APPID',
                'alipaypublicmck_key' => '支付宝公钥',
                'appprivatemck_key' => '应用私钥'
            ],
            'cookie' => 'xfqymckxy',
            'check_field' => ['field' => 'alipayUId', 'value' => 'alipaymck_uid']
        ],
        5 => [
            'fields' => [
                'alipaydmf_appid' => '支付宝APPID',
                'alipaypublicdmf_key' => '支付宝公钥',
                'appprivatedmf_key' => '应用私钥'
            ],
            'cookie' => 'xfqydmfxy',
            'check_field' => ['field' => 'alipayAppId', 'value' => 'alipaydmf_appid']
        ]
    ];

    // 支付类型映射
    protected $paymentHandlers = [
        'alipay' => 'handleAlipayPayment',
        'qqpay' => 'handleQQPayment',
        'wxpay' => 'handleWxPayment'
    ];

    // 微信支付类型配置
    protected $wxPayConfigs = [
        '1' => [
            'fields' => [
                'qr_url' => '二维码链接',
                'wx_name' => '绑定店员',
                'beizhu' => '微信名称'
            ],
            'hook_type' => 0
        ],
        '2' => [
            'fields' => [
                'mactype' => 'Mac协议挂机方式',
                'beizhu' => '微信名称'
            ],
            'hook_type' => 2
        ],
        '3' => [
            'fields' => [
                'Uostype' => 'Uos协议挂机方式',
                'beizhu' => '微信名称',
                'qr_url' => '二维码链接'
            ],
            'hook_type' => 2
        ],
        '4' => [
            'fields' => [
                'Ipadtype' => 'IPAD协议挂机方式',
                'beizhu' => '微信名称'
            ],
            'hook_type' => 2
        ]
    ];

    // 文件上传处理
    public function Upload() {
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }

        $rand = date("YmdHis") . rand(11111, 99999);
        $imgname = PUBLICROOT . 'upload/' . $rand . '.png';
        $qrurl = $this->httphost . 'upload/' . $rand . '.png';
        
        if(!copy($_FILES['file']['tmp_name'], $imgname)) {
            exitjson(-1, '上传失败！');
        }

        $res = $this->CurlUrl->imgdecrypt($qrurl);
        unlink($imgname);

        if($res['code'] == -2) {
            exitjson(-1, $res['msg'], ['qr_url' => "请删除此文字并前往草料二维码 进行解码粘贴并添加"]);
        } elseif($res['code'] == 1) {
            exitjson(200, '解码成功', ['qr_url' => $res['qrurl']]);
        }
        exitjson(-1, $res['msg']);
    }
    // 文件上传处理
    public function Upload1() {
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }

        $rand = date("YmdHis") . rand(11111, 99999);
        $imgname = PUBLICROOT . 'upload/' . $rand . '.png';
        $qrurl = $this->httphost . 'upload/' . $rand . '.png';
        
        if(!copy($_FILES['file']['tmp_name'], $imgname)) {
            exitjson(-1, '上传失败！');
        }

       exitjson(200, '解码成功', ['qr_url' => $qrurl]);
       
    }
    public function info_qrlist(){
        if($this->islogin_user != 1 )exitjson(-1,"请先登录");
        $status = $this->getQrlistStats();
        $formattedStats  = $this->formatStats($status);
        exitjson(200,'success',$formattedStats);
    }
    
    protected function getQrlistStats(){
        $columns = "
            SUM(CASE 
                WHEN type = 'wxpay' AND status = 1 THEN 1 
                ELSE 0 
            END) as wxpay_success,
            SUM(CASE 
                WHEN type = 'wxpay' AND status = 0 THEN 1 
                ELSE 0 
            END) as wxpay_fail,
            SUM(CASE 
                WHEN type = 'wxpay' THEN 1 
                ELSE 0 
            END) as wxpay_total,
            
            SUM(CASE 
                WHEN type = 'alipay' AND status = 1 THEN 1 
                ELSE 0 
            END) as alipay_success,
            SUM(CASE 
                WHEN type = 'alipay' AND status = 0 THEN 1 
                ELSE 0 
            END) as alipay_fail,
            SUM(CASE 
                WHEN type = 'alipay' THEN 1 
                ELSE 0 
            END) as alipay_total,
            
            SUM(CASE 
                WHEN type = 'qqpay' AND status = 1 THEN 1 
                ELSE 0 
            END) as qqpay_success,
            SUM(CASE 
                WHEN type = 'qqpay' AND status = 0 THEN 1 
                ELSE 0 
            END) as qqpay_fail,
            SUM(CASE 
                WHEN type = 'qqpay' THEN 1 
                ELSE 0 
            END) as qqpay_total,
            SUM(CASE 
                WHEN type = 'usdt' AND status = 1 THEN 1 
                ELSE 0 
            END) as usdt_success,
            SUM(CASE 
                WHEN type = 'usdt' AND status = 0 THEN 1 
                ELSE 0 
            END) as usdt_fail,
            SUM(CASE 
                WHEN type = 'usdt' THEN 1 
                ELSE 0 
            END) as usdt_total,
            count(*) as count
            ";
        $conditions  = [
            'pid'=>$this->uid
        ];
        $result = $this->db->complexSelect('qrlist', $columns, $conditions);
        return $result['result'][0] ?? null;
    }
    protected function formatStats($stats) {
        return [
            'wxpay' => [
                'success' => (int)$stats['wxpay_success'],
                'fail' => (int)$stats['wxpay_fail'],
                'total' => (int)$stats['wxpay_total']
            ],
            'alipay' => [
                'success' => (int)$stats['alipay_success'],
                'fail' => (int)$stats['alipay_fail'],
                'total' => (int)$stats['alipay_total']
            ],
            'qqpay' => [
                'success' => (int)$stats['qqpay_success'],
                'fail' => (int)$stats['qqpay_fail'],
                'total' => (int)$stats['qqpay_total']
            ],
            'usdt' => [
                'success' => (int)$stats['usdt_success'],
                'fail' => (int)$stats['usdt_fail'],
                'total' => (int)$stats['usdt_total']
            ],
            'allqrlist'=>(int)$stats['count'],
            'maxqrlist'=>(int)$this->conf->qr_nums ?: $this->userrow['qr_nums']
        ];
    }
    // 添加二维码入口
    public function Add_qrlist($get, $post, $data) {
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }

        $params = array_filter($data, fn($v) => $v !== '');
        
        if(empty($params['type'])) {
            exitjson(-1, '请选择一个支付通道');
        }

        $this->Typeissue($params);
    }
    public function edit_qrlist($get, $post, $data){
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }
        unset($data['id']);
        $id = $this->input->id;
        if(empty($id))exitjson(-1,'非法操作！');
        $row = $this->db->qrlistrow($id,'id','`id`,`pid`');
        if(empty($row) || $row['pid'] != $this->uid)exitjson(-1,'数据不存在！');
        $params = array_filter($data, fn($v) => $v !== '');
        
        if($this->db->update("qrlist",$params,['id'=>$id])){
            exitjson(200,'修改成功！');
        }
        exitjson(-1,'修改失败！');
    }
    public function del_qrlist(){
        if($this->islogin_user != 1) {
            exitjson(-1, "请先登录");
        }
        $id = $this->input->id;
        if(empty($id))exitjson(-1,'非法操作！');
        $row = $this->db->qrlistrow($id,'id','`id`,`pid`');
        if(empty($row) || $row['pid'] != $this->uid)exitjson(-1,'数据不存在！');
        if($this->db->delete('qrlist',['id'=>$id])){
            exitjson(200,'删除成功！');
        }
        exitjson(-1,'非法操作！');
    }

    // 支付类型分发
    protected function Typeissue($params) {
        $this->validateBasicRequirements($params['type']);
        
        if(!isset($this->paymentHandlers[$params['type']])) {
            exitjson(-1, '未知通道');
        }

        $handler = $this->paymentHandlers[$params['type']];
        $this->$handler($params);
    }

    // 支付宝支付处理
    protected function handleAlipayPayment($params) {
        if(empty($params['alipay'])) {
            exitjson(-1, '请选择一个挂机协议');
        }

        $alipayType = $params['alipay'];
        
        if(isset($this->alipayConfigs[$alipayType])) {
            $this->ErrorTips($params, $this->alipayConfigs[$alipayType]['fields']);
            $params = $this->processConfiguredAlipay($params, $alipayType);
        } elseif(in_array($alipayType, [1, 2, 3])) {
            $params = $this->processSimpleAlipay($params);
        } else {
            exitjson(-1, '协议参数不合法！');
        }

        $this->insertQrlist($params);
    }

    // QQ支付处理
    protected function handleQQPayment($params) {
        if(empty($params['qqpay'])) {
            exitjson(-1, '请选择一个挂机协议');
        }
        if(empty($params['beizhu']) || !is_numeric($params['beizhu'])) {
            exitjson(-1, '收款QQ不合法或为空');
        }

        $qqpay = $params['qqpay'];
        unset($params['qqpay']);

        $data = $this->prepareCommonData(0, 0, 0) + [
            'xf_type' => $qqpay,
            'xf_stat' => ($qqpay == '1') ? 0 : 1
        ];

        $this->insertQrlist(array_merge($params, $data));
    }

    // 微信支付处理
    protected function handleWxPayment($params) {
        if(empty($params['wxpay'])) {
            exitjson(-1, '请选择一个挂机方式');
        }

        $wxType = $params['wxpay'];
        if(!isset($this->wxPayConfigs[$wxType])) {
            exitjson(-1, '未知的微信支付方式');
        }

        $config = $this->wxPayConfigs[$wxType];
        $this->ErrorTips($params, $config['fields']);

        $params = $this->processWxPay($params, $wxType, $config);
        $this->insertQrlist($params);
    }

    // 处理支付宝配置支付
    protected function processConfiguredAlipay($params, $alipayType) {
        $config = $this->alipayConfigs[$alipayType];
        $checkField = $config['check_field'];
        $fieldValue = $params[$checkField['value']];
        
        // 检查重复添加
        $res = $this->db->qrlistrow($fieldValue, $checkField['field'], "`pid`,`cookie`,`id`");
        if($res && $res['pid'] == $this->uid) {
            if($alipayType == 4) {
                $this->checkExistingCookie($fieldValue);
            }
            exitjson(-1, '添加失败,该账号已存在');
        }

        // 准备数据
        $data = $this->prepareAlipayData($params, $config);
        
        // 移除配置相关字段
        foreach(array_keys($config['fields']) as $field) {
            unset($params[$field]);
        }
        unset($params['alipay']);

        return array_merge($params, $data);
    }

    // 处理简单支付宝支付
    protected function processSimpleAlipay($params) {
        $alipayType = $params['alipay'];
        unset($params['alipay']);

        return array_merge($params, $this->prepareCommonData(0, 0, 0) + [
            'xf_type' => $alipayType
        ]);
    }

    // 处理微信支付
    protected function processWxPay($params, $wxType, $config) {
        $data = $this->prepareCommonData($config['hook_type'], 0, 0);
        
        switch($wxType) {
            case '1':
                
                $row = $this->db->wechat_trumpetrow($params['wx_name'], 'wx_user', 'id');
                
                if(empty($row)) {
                    exitjson(-1, '店员账号不存在！');
                }
                $params['wx_name'] = $row['wx_name'];
                $data['xf_type'] = 1;
                $data['xf_stat'] = 0;
                break;
                
            case '2':
                if(in_array($params['mactype'], ['8', '9', '10']) && empty($params['qr_url'])) {
                    exitjson(-1, '收款码URL不可为空');
                }
                $data['wxyunurl'] = $params['macwxyunurl'] ?? '';
                $data['xf_type'] = $params['mactype'];
                unset($params['mactype'], $params['macwxyunurl']);
                break;
                
            case '3':
                $data['wxyunurl'] = $params['uoswxyunurl'] ?? '';
                $data['xf_type'] = $params['Uostype'];
                unset($params['Uostype'], $params['uoswxyunurl']);
                break;
                
            case '4':
                $data['wxyunurl'] = $params['ipadwxyunurl'] ?? '';
                $data['xf_type'] = $params['Ipadtype'];
                unset($params['Ipadtype'], $params['ipadwxyunurl']);
                break;
        }

        unset($params['wxpay']);
        return array_merge($params, $data);
    }

    // 准备支付宝数据
    protected function prepareAlipayData($params, $config) {
        $fields = $config['fields'];
        $fieldMap = [
            'alipaymck_appid' => 'alipayAppId',
            'alipaydmf_appid' => 'alipayAppId',
            'alipaypublicmck_key' => 'alipayPublicKey',
            'alipaypublicdmf_key' => 'alipayPublicKey',
            'appprivatemck_key' => 'appPrivateKey',
            'appprivatedmf_key' => 'appPrivateKey',
            'alipaymck_uid' => 'alipayUId'
        ];

        $data = $this->prepareCommonData(0, 1, $config['cookie']);

        foreach($fields as $field => $label) {
            if(isset($params[$field]) && isset($fieldMap[$field])) {
                $data[$fieldMap[$field]] = $params[$field];
            }
        }

        return $data;
    }

    // 检查已存在的Cookie
    protected function checkExistingCookie($uid) {
        $qr_row = $this->db->select('qrlist', "`id`,`cookie`", ['pid' => $this->uid, 'hook_type' => 0]);
        if($qr_row['count'] > 0) {
            foreach($qr_row['result'] as $row) {
                if(!empty($row['cookie'])) {
                    $decodedCookie = base64_decode($row['cookie']);
                    $userId = getSubstr($decodedCookie, "CLUB_ALIPAY_COM=", ";");
                    if($userId == $uid) {
                        exitjson(-1, '添加失败，此账号已存在');
                    }
                }
            }
        }
    }

    // 基础验证
    protected function validateBasicRequirements($type) {
        $this->qrlistnum();
        $this->user_vip($type);
    }

    // 数据库插入
    protected function insertQrlist($params) {
        if($this->db->insert('qrlist', $params)) {
            exitjson(200, '添加成功！');
        }
        exitjson(-1, '添加失败！');
    }

    // 准备通用数据
    protected function prepareCommonData($hookType = 0, $status = 0, $cookie = 0) {
        return [
            'pid' => $this->uid,
            'cookie' => $cookie,
            'money' => 0.00,
            'status' => $status,
            'hook_type' => $hookType,
            'addtime' => $this->date
        ];
    }

    // 参数验证
    protected function ErrorTips($params, $fields) {
        foreach($fields as $field => $fieldName) {
            if(empty($params[$field])) {
                exitjson(-1, "{$fieldName}不能为空");
            }
        }
        return true;
    }

    // 配额检查
    protected function qrlistnum() {
        $num = $this->db->qrlistnum($this->uid);
        $maxNum = $this->conf->qr_nums ?: $this->userrow['qr_nums'];
        if($num > $maxNum) {
            exitjson(-1, '您的配额已上限，请购买配额再次上传！');
        }
    }

    // 会员验证
    protected function user_vip($type) {
        $typeName = strip_tags(pay_type($type));
        $huiyuan = ($type == 'usdt') ? 'alipay' : $type;
        $vipTimeKey = $huiyuan . '_free_vip_time';
        
        if(strtotime($this->userrow[$vipTimeKey]) < strtotime($this->date)) {
            $usdt = ($type == 'usdt') ? '(开通支付宝会员)' : '';
            exitjson(-1, "您暂未开通{$typeName}{$usdt}会员 请开通后再试！");
        }
    }
}
?>